package cn.accjiyun.controller.sale;

import cn.accjiyun.common.controller.BaseController;
import cn.accjiyun.common.entity.PageModel;
import cn.accjiyun.common.entity.QueryEntity;
import cn.accjiyun.common.utils.WebUtils;
import cn.accjiyun.entity.sale.Customer;
import cn.accjiyun.entity.sale.Orders;
import cn.accjiyun.service.sale.CustomerService;
import cn.accjiyun.service.sale.OrdersService;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by jiyun on 2017/5/3.
 */
@Controller
@RequestMapping("/admin/sale")
public class AdminOrdersController extends BaseController {
    private static Logger logger = LoggerFactory.getLogger(AdminOrdersController.class);
    private static String addOrdersPage = getViewPath("/admin/sale/orders-add");
    private static String ordersListPage = getViewPath("/admin/sale/orders-list");

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CustomerService customerService;

    @InitBinder({"orders"})
    public void initBinderSysUser(WebDataBinder binder) {
        binder.setFieldDefaultPrefix("orders.");
    }

    /**
     * 创建客户
     *
     * @return Map<String,Object>
     */
    @RequestMapping("/createOrders")
    @ResponseBody
    public String createOrders(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String variety = request.getParameter("variety");
            Integer count = Integer.valueOf(request.getParameter("count").trim());
            Integer realPrice = Integer.valueOf(request.getParameter("realPrice").trim());
            Timestamp createTime = WebUtils.stringToTimestamp(request.getParameter("createTime").trim());
            int customerId = Integer.valueOf(request.getParameter("customerId").trim());
            Customer customerByCustomerId = customerService.queryCustomerById(customerId);

            Orders orders = new Orders();
            orders.setVariety(variety);
            orders.setCount(count);
            orders.setRealPrice(realPrice);
            orders.setCreateTime(createTime);
            orders.setCustomerByCustomerId(customerByCustomerId);

            ordersService.createOrders(orders);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "添加成功");
            resultJson.addProperty("url", "/admin/sale/ordersList");
        } catch (Exception e) {
            logger.error("AdminOrders.createOrders()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "添加失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/deleteOrders")
    @ResponseBody
    public String deleteOrders(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            String[] ordersIdsString = request.getParameter("ordersId").split(",");
            int[] ordersIds = new int[ordersIdsString.length];
            for (int i = 0; i < ordersIdsString.length; i++) {
                ordersIds[i] = Integer.valueOf(ordersIdsString[i]);
            }
            if (ordersIdsString != null && ordersIdsString.length > 0) {
                ordersService.deleteOrders(ordersIds);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("msg", "删除成功");
            resultJson.addProperty("url", "reload");
        } catch (Exception e) {
            logger.error("AdminOrdersController.deleteOrders()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "删除失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/getOrdersList")
    @ResponseBody
    public String getOrdersList(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            QueryEntity queryEntity = new QueryEntity();
            Map likeStrings = new HashMap();
            String keyword = request.getParameter("keyword");
            if (WebUtils.isValidateRealString(keyword)) {
                likeStrings.put("variety", keyword);
            }
            queryEntity.setLikeStrings(likeStrings);
            queryEntity.setBeginCreateTime(WebUtils.stringToData(request.getParameter("start_date")));
            queryEntity.setEndCreateTime(WebUtils.stringToData(request.getParameter("end_date")));
            queryEntity.setDateKeyword("createTime");
            PageModel<Orders> page = new PageModel();
            page.setPageSize(5);
            int pageNo = Integer.valueOf(request.getParameter("pageNo"));
            page.setPageNo(pageNo);
            List<Orders> ordersList = ordersService.queryOrdersPage(queryEntity, page);
            JsonArray array = new JsonArray();
            for (Orders orders : ordersList) {
                JsonObject list = new JsonObject();
                list.addProperty("ordersId", orders.getOrdersId());
                list.addProperty("variety", orders.getVariety());
                list.addProperty("count", orders.getCount());
                list.addProperty("realPrice", orders.getRealPrice());
                list.addProperty("createTime", WebUtils.timestampToString(orders.getCreateTime()));
                list.addProperty("customerName", orders.getCustomerByCustomerId().getCustomerName());
                list.addProperty("customerId", orders.getCustomerByCustomerId().getCustomerId());
                array.add(list);
            }
            resultJson.addProperty("status", 200);
            resultJson.addProperty("pages", page.getTotalPageSize());
            JsonObject list = new JsonObject();
            list.add("list", array);
            resultJson.add("data", list);
        } catch (Exception e) {
            logger.error("AdminOrdersController.getOrdersList()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "获取列表失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/updateOrders")
    @ResponseBody
    public String updateOrders(HttpServletRequest request) {
        JsonObject resultJson = new JsonObject();
        try {
            int ordersId = Integer.valueOf(request.getParameter("ordersId"));
            String variety = request.getParameter("variety");
            Integer count = Integer.valueOf(request.getParameter("count").trim());
            Integer realPrice = Integer.valueOf(request.getParameter("realPrice").trim());
            Timestamp createTime = WebUtils.stringToTimestamp(request.getParameter("createTime").trim());
            int customerId = Integer.valueOf(request.getParameter("customerId").trim());
            Customer customerByCustomerId = customerService.queryCustomerById(customerId);

            Orders orders = ordersService.queryOrdersById(ordersId);
            orders.setVariety(variety);
            orders.setCount(count);
            orders.setRealPrice(realPrice);
            orders.setCreateTime(createTime);
            orders.setCustomerByCustomerId(customerByCustomerId);

            ordersService.updateOrders(orders);
            resultJson.addProperty("status", 200);
            resultJson.addProperty("url", "reload");
            resultJson.addProperty("msg", "更新成功");
        } catch (Exception e) {
            logger.error("AdminOrders.updateOrders()--error", e);
            resultJson.addProperty("status", 400);
            resultJson.addProperty("msg", "更新失败！");
        }
        logger.info(gson.toJson(resultJson));
        return gson.toJson(resultJson);
    }

    @RequestMapping("/ordersAdd")
    public ModelAndView initUserAddPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("customerList", customerService.createQuery("from Customer", null));
        model.setViewName(addOrdersPage);
        return model;
    }

    @RequestMapping("/ordersList")
    public ModelAndView initUserListPage() {
        ModelAndView model = new ModelAndView();
        model.addObject("customerList", customerService.createQuery("from Customer", null));
        model.setViewName(ordersListPage);
        return model;
    }

}
